package cn.edu.jsu.official.service.serviceImpl;

import cn.edu.jsu.official.dao.AdminDao;
import cn.edu.jsu.official.dao.VisitorDao;

import cn.edu.jsu.official.pojo.dto.*;
import cn.edu.jsu.official.pojo.vo.*;
import cn.edu.jsu.official.service.VisitorService;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.*;
/**
 * @author Mo
 * @createTime 2022/3/2 23:10
 * @description
 */
@Service
public class VisitorServiceImpl implements VisitorService {
    @Autowired
    private VisitorDao visitorDao;

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private GridFSBucket gridFSBucket;

    @Override
    public CommonResult queryAllProjectAchievement() {
        List<ProjectAchievement> list = visitorDao.findAllProjectAchievement();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllContestAchievement() {
        List<ContestAchievement> list=visitorDao.findAllContestAchievement();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllProjectInProgress() {
        List<ProjectInProgressInfo> list=visitorDao.findAllProjectInProgress();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllCopyright() {
        List<CopyrightInfo> list = visitorDao.findAllCopyright();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllMemberInfo() {
        List<MemberInfo> list = visitorDao.findAllMemberInfo();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllGoalInfo() {
        List<GoalInfo> list=visitorDao.findAllGoalInfo();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllContestInfo() {
        List<ContestInfo> list = visitorDao.findAllProjectInfo();
        return new CommonResult(200,"查询成功",list);
    }

    @Override
    public CommonResult queryAllHistoryProcess() {
        List<HistoryProcess> historyProcessList = visitorDao.findAllHistoryProcess();
        List<HistoryVO> historyVOList= ConsolidateDataByYear(historyProcessList);
        return new CommonResult(200, "查询成功", historyVOList);
    }

    @Override
    public CommonResult queryArticle(String articleId) {
        ArticleVO articleVO = visitorDao.queryArticle(articleId);
        if(null == articleVO) {
            return new CommonResult(444, "无数据");
        } else {
            return new CommonResult(200, "成功", articleVO.getContent());

        }
//        String fileStream = new String(bytes, StandardCharsets.UTF_8);
//        return new CommonResult(200, "查询文件成功", fileStream);
    }

    @Override
    public CommonResult queryImage(String imageId, HttpServletRequest request, HttpServletResponse response) {
        try {
            String base64 = image2Base64(imageId);
            if (base64 == null) {
                return new CommonResult(444, "图片为空");
            } else {
                return new CommonResult(200, "查询成功", base64);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(444, "查询图片失败");
        }
    }

    @Override
    public CommonResult countAchievements() {
        int copyrightNum = (int) adminDao.countCopyright();
        int contestAchievementNum = (int) adminDao.countContestAchievement();
        int projectAchievementNum = (int) adminDao.countProjectAchievement();
        AchievementsNumberVO achievementsNumberVO = new AchievementsNumberVO(copyrightNum, contestAchievementNum, projectAchievementNum);
        return new CommonResult<AchievementsNumberVO>(200, "查询成功", achievementsNumberVO);
    }

    @Override
    public CommonResult queryAllMemberWithImage(Integer condition) {
        List<MemberVO> memberVOS = visitorDao.queryAllMemberWithImage(condition);
        if (memberVOS == null) {
            return new CommonResult(444, "数据为空");
        }
        memberVOS.forEach(memberVO -> {
            try {
                memberVO.setBase64(image2Base64(memberVO.getMemberImageId().toString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return new CommonResult(200, "查询成功", memberVOS);
    }

    @Override
    public CommonResult countAchievementNumberGroupByYears(Integer queryType){
        if (queryType >= 1 && queryType <= 3) {
            //  TODO 查询项目成就数量
            return new CommonResult(200, "查询成功", visitorDao.countAchievementNumberGroupByYears(queryType));
        } else {
            return new CommonResult(444, "未知查询数据类型");
        }
    }

    public CommonResult downLoadFile(String fileId, HttpServletRequest request, HttpServletResponse response) {
//        GridFSFile gridFSFile = visitorDao.queryArticle(fileId);
//        if (gridFSFile == null) {
//            return new CommonResult(444, "文件不存在");
//        }
//        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//        GridFsResource resource = new GridFsResource(gridFSFile, gridFSDownloadStream);
//        byte[] bytes = null;
        return null;
    }

    public String image2Base64(String imageId) throws Exception {
        GridFSFile gridFSFile = visitorDao.queryImage(imageId);
        if (gridFSFile == null) {
            return null;
        }
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource resource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        byte[] bytes = null;
        bytes = IOUtils.toByteArray(resource.getInputStream());
//        ServletOutputStream out = response.getOutputStream();
//        out.write(bytes);
//        out.flush();
//        out.close();

        String encode = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(bytes);
        return encode;
    }

    @Override
    public CommonResult queryAllTechStackInfo() {
        return new CommonResult(200, "查询成功", visitorDao.queryAllTechStackInfo());
    }

    @Override
    public CommonResult queryChooseMember() {
        return new CommonResult(200,"查询成功",visitorDao.queryChooseMember());
    }


    private List<HistoryVO> ConsolidateDataByYear(List<HistoryProcess> list) {
        List<String> stringList = new ArrayList<>();
        List<HistoryVO> historyVOList = new ArrayList<>();
        for(int i=0;i<list.size();i++){
            int flag=0;
            String str = String.valueOf(list.get(i).getEventDate()).substring(String.valueOf(list.get(i).getEventDate()).length()-4);
            stringList.add(str);
            List<HistoryProcess> historyProcessList = new ArrayList<>();
            for(int j=0;j<historyVOList.size();j++){
                if(historyVOList.get(j).getYear().equals(Integer.valueOf(str))){
                    flag=1;
                }
            }
            if(flag==0){
                historyVOList.add(new HistoryVO(Integer.valueOf(str), historyProcessList));
            }

        }
        for(int i=0;i<historyVOList.size();i++){
            for(int j=0;j<list.size();j++){
                if(String.valueOf(list.get(j).getEventDate()).contains(historyVOList.get(i).getYear().toString())){
                    historyVOList.get(i).getChildHistoryProcesses().add(list.get(j));
                }
            }
        }
        Collections.sort(historyVOList, new Comparator<HistoryVO>() {
            @Override
            public int compare(HistoryVO o1, HistoryVO o2) {
                return o1.getYear()-o2.getYear();
            }
        });
        return historyVOList;
    }
}
